<template>
  <view class="consult-box" >
    <u-navbar :is-back="false" title="骑手咨询中心"></u-navbar>

    <u-form :model="form" ref="uForm"  label-width="130">
      <u-form-item label="姓名" prop="ridersName" required><u-input v-model="form.ridersName" /></u-form-item>
      <u-form-item label="手机号码" prop="ridersPhone" required>
        <u-input v-model="form.ridersPhone" placeholder="请输入手机号码" />
      </u-form-item>
      <u-form-item label="归属站点"  prop="sideName" required>
        <u-input v-model="form.sideName" type="select" @click="showPickerMax($event)" placeholder="请选择归属站点" />
      </u-form-item>
      <u-form-item label="是否匿名" required>
        <u-radio-group v-model="form.anonymous"  @change="changeAnonymous">
          <u-radio v-for="(item, index) in radioList" :key="index" :name="item.value" :disabled="item.disabled">
            {{ item.name }}
          </u-radio>
        </u-radio-group>
      </u-form-item>
      <u-form-item label="是否在职" required>
        <u-radio-group v-model="form.isJob"  >
          <u-radio v-for="(item, index) in radioList" :key="index" :name="item.value" :disabled="item.disabled">
            {{ item.name }}
          </u-radio>
        </u-radio-group>
      </u-form-item>
      <u-form-item label="是否离职到期" required v-if="form.isJob == '0'">
        <u-radio-group v-model="form.isResign"  >
          <u-radio v-for="(item, index) in radioList" :key="index" :name="item.value" :disabled="item.disabled">
            {{ item.name }}
          </u-radio>
        </u-radio-group>
      </u-form-item>
      <u-form-item label="咨询分类"  prop="questionLabel" required >
        <u-input v-model="form.questionLabel" type="select" :select-open="leibieShow" @click="leibieShow = true"
                 placeholder="请选择咨询分类" />
      </u-form-item>
      <u-form-item label="咨询内容" prop="demands" required>
        <u-input v-model="form.demands" :type="'textarea'" :border="true" :height="150" :auto-height="true" />
      </u-form-item>
      <u-form-item label="是否有证据需要提供" prop="isEvidence" required>
        <u-radio-group v-model="form.isEvidence"  >
          <u-radio v-for="(item, index) in radioList" :key="index" :name="item.value" :disabled="item.disabled">
            {{ item.name }}
          </u-radio>
        </u-radio-group>
      </u-form-item>
      <u-form-item  label="视频上传" prop="dormitoryVideo">
        <cl-upload  v-model="videoList" cloudType="other" :compressed="true" :headers="uploadHeader" :listStyle="{
              columns: 2,
              columnGap: '20rpx',
              rowGap:'20rpx',
              height:'166rpx',
              radius:'20rpx'
          }" :action="clUplodUrl2"  :maxVideo="1" @onSuccess="onSuccess"  @onDelete="onDelete" fileType="video" :sourceType="['camera ', 'album']">
          <template v-slot:addImg>
            <view class="newAddImg">
              <u-icon  name="plus" size="40"></u-icon>
              <text >选择视频</text>
            </view>
          </template>
        </cl-upload>
      </u-form-item>
      <u-form-item  label="图片上传" prop="bedImages">
        <u-upload :source-type="['album', 'camera']" width="160" height="160" :header="uploadHeader"  :action="clUplodUrl" @on-remove="uploadRemove" @on-success="uploadSuccess"
                  ref="handIdCardUpload" ></u-upload>
      </u-form-item>
      <u-form-item  label="音频上传" prop="bedImages">

        <view class="list-item-file"  v-for="(item,index) in audioList">
          <view class="list-item-file-deleteImg" @click="remove(item,index)">
            <u-icon size="40" name="close-circle"></u-icon>
          </view>
          <u-image :src="`${proxyUrl}/static/yinpin.png`"  mode="widthFix" width="160rpx" height="160rpx" style="margin-top:5px" @click="playAudio(item)"></u-image>
        </view>
        <view class="list-item" @click="record">
          <u-icon name="plus" size="40"></u-icon>
          <view>选择音频</view>
        </view>
<!--        <u-upload :source-type="['album', 'camera']" width="160" height="160" :header="uploadHeader"  :action="clUplodUrl" @on-remove="uploadRemove" @on-success="uploadSuccess"-->
<!--                  ref="handIdCardUpload" ></u-upload>-->
      </u-form-item>
    </u-form>
    <u-button type="primary" @click="submitFunc">提交</u-button>
    <u-select v-model="leibieShow" :list="leibieList" mode="single-column" @confirm="leibieCallback"></u-select>

    <u-modal v-model="showPopup" :title-style="{color: 'red'}" :title="'播放音频'">
      <view class="slot-content">
        <view style="display: flex;justify-content: center;align-items: center;padding: 30rpx;">
          <audio :src="activeUrl" ></audio>
        </view>
      </view>
    </u-modal>

    <nui-picker ref="picker" :title="auiPicker.title" :layer="auiPicker.layer" :data="auiPicker.data"
                @callback="pickerCallback"></nui-picker>
  </view>
</template>

<script>
import nuiPicker from "@/components/picker.vue";
import clUpload from "../../uni_modules/cl-upload/components/cl-upload/cl-upload.vue";
import {isEmpty} from "@/utils";
import * as consts from "@/utils/constant.js";
export default {
  components: {
    clUpload,
    nuiPicker
  },
  data() {
    return {
      showPopup:false,
      proxyUrl:(window.location.href.includes('/xsdcrm-wechat-ui/')?'/xsdcrm-wechat-ui/': ''),
      uploadHeader:{
        // Authorization:"Bearer " + uni.getStorageSync("token")
      },
      clUplodUrl:consts.API_BASE_URL + '/xsdcrm-wechat-api/riders/learningseek/uploadFile',
      clUplodUrl2:consts.API_BASE_URL + '/xsdcrm-wechat-api/riders/learningseek/uploadFile',
      videoList:[],
      leibieShow: false,
      leibieList:[],
      rules: {
        ridersName: {
          type: 'string',
          required: true,
          message: '请输入骑手姓名',
          trigger: ['blur', 'change']
        },
        ridersId: {
          type: 'string',
          required: true,
          message: '请输入骑手id',
          trigger: ['blur', 'change']
        },
        ridersPhone: {
          type: 'string',
          required: true,
          message: '请填写手机号码',
          trigger: ['blur', 'change']
        },
        sideName: {
          type: 'string',
          required: true,
          message: '请选择站点',
          trigger: ['blur', 'change']
        },
        questionLabel: {
          type: 'string',
          required: true,
          message: '请选择问题分类',
          trigger: ['blur', 'change']
        },
        demands: {
          type: 'string',
          required: true,
          message: '请填写骑手诉求',
          trigger: ['blur', 'change']
        },
        isEvidence: {
          type: 'string',
          required: true,
          message: '请选择是否有证据需要提供',
          trigger: ['blur', 'change']
        },
        isJob: {
          type: 'string',
          required: true,
          message: '请选择是否在职',
          trigger: ['blur', 'change']
        },
        isResign: {
          type: 'string',
          required: true,
          message: '请选择是否离职到期',
          trigger: ['blur', 'change']
        },
        riderPictureFront: {
          type: 'string',
          required: true,
          message: '请上传借款人身份证正面照片！',
          trigger: ['blur', 'change']
        },
        riderPictureVerso: {
          type: 'string',
          required: true,
          message: '请上传借款人身份证反面照片！',
          trigger: ['blur', 'change']
        },
        riderIdcardPic: {
          type: 'string',
          required: true,
          message: '请上传骑手手持身份证照片！',
          trigger: ['blur', 'change']
        }
      },
      auiPicker: {
        title: "选择站点",
        layer: null,
        data: [],
      },
      form: {
        anonymous:'0',
        ridersLearningCenterSeekMatialList:[]
      },
      radioList: [
        {
          name: '是',
          value: '1',
          disabled: false
        },
        {
          name: '否',
          value: '0',
          disabled: false
        }
      ],
      radio: '',
      switchVal: false,
      siteItem: {},
      audioList:[],
      activeUrl:'',
      oldForm:{},
      fileList1:[],
      fileList2:[],
      fileList3:[]
    };
  },
  onLoad(option) {
    this.getRidersPhoneInfo(option)
    this.getDeptList();
    this.getBankDictList();
  },
  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
  methods: {
    async getRidersPhoneInfo(option){
      let {data} = await  this.$api.dormitory.getRidersPhoneInfo({ridersPhone:option.mobile,idCard:option.idCard})
      if (!isEmpty(data.ridersName)) {
        this.form.ridersName = data.ridersName
        this.form.ridersId = data.ridersId
        this.form.ridersPhone = data.ridersPhone
        this.form.sideName = data.sideName
        this.form.sideId = data.sideId
        this.$forceUpdate()
      }
    },
    submitFunc(){
      uni.showModal({
        title: '提示',
        content: `请确认信息填写无误并提交咨询?`,
        success: (res)=> {
          if (res.confirm) {
            this.$refs.uForm.validate(async (valid) => {
              if (valid) {
                  this.form.ridersLearningCenterSeekMatialList = [...this.fileList1,...this.fileList2,...this.fileList3]

                  // if (this.form.ridersLearningCenterSeekMatialList.length == 0) {
                  //   uni.showToast({title:'请至少上传一种相关文件！',icon:'none'})
                  //   return
                  // }

                  let form = JSON.parse(JSON.stringify(this.form))
                  if (this.form.anonymous == '1'){
                    form.ridersName = this.oldForm.ridersName
                    form.ridersPhone = this.oldForm.ridersPhone
                    form.sideName = this.oldForm.sideName
                  }

                  let {code} = await this.$api.dormitory.learningseek(form)
                  if (code == 200) {
                    uni.reLaunch({
                      url: `/pages/rider-center/webIndex-success`
                    })
                  }
              }
            })
          } else if (res.cancel) {

          }
        }
      });
    },
    changeAnonymous(e){
      if ((isEmpty(this.form.ridersName) || isEmpty(this.form.ridersPhone) || isEmpty(this.form.sideName)) && e==1) {
        uni.showToast({title:'请将姓名、手机号、站点信息填写完整后进行匿名操作！',icon:'none'})
        this.$nextTick(()=>{
          this.form.anonymous = '0'
          this.$forceUpdate();
        })
        return
      }
      const that = this;
      function hiddenStr(str) {
        console.log(!that.form[str]?.includes('*') && e == '1')
        if (that.form[str] && !that.form[str]?.includes('*') && e == '1') {
          that.oldForm[str] = JSON.parse(JSON.stringify(that.form[str]))
          that.form[str] = that.hideMiddleCharacters(that.form[str])
        } else {
          that.form[str] = !isEmpty(that.form[str])?(!isEmpty(that.oldForm[str])?that.oldForm[str]:that.form[str]):''
        }
      }
      hiddenStr('ridersName')
      hiddenStr('ridersPhone')
      hiddenStr('sideName')
      console.log(that.form.ridersPhone)
      this.$forceUpdate();
    },
    hideMiddleCharacters(input) {
      console.log(input)
      // 如果输入的字符串长度小于等于2，则无需隐藏
      if (input.length <= 2) {
        return input.substr(0, 1) + '*'; // 姓名为两字符时，隐藏第二个字符
      }
      // 判断是否是身份证号码
      if (/^\d{18}$/.test(input)) {
        // 身份证号：保留前三位和后四位，中间部分用*替代
        return input.substr(0, 3) + '*'.repeat(input.length - 7) + input.substr(input.length - 4);
      }
      // 判断是否是姓名，姓名一般不会超过20个字符，且通常包含中文
      if (/^[\u4e00-\u9fa5]{2,20}$/.test(input)) {
        // 姓名：保留首尾字符，隐藏中间的一个字符
        return input.substr(0, 1) + '*' + input.substr(input.length - 1);
      }
      // 对于其他情况，按照原有规则处理
      // 获取需要隐藏的字符数量
      var hideCount = input.length - 6;
      // 计算需要替换的起始位置和长度
      var start = Math.floor((input.length - hideCount) / 2);
      var replaceLength = input.length - (start * 2);
      // 构造替换的字符串
      var replaceStr = '*'.repeat(replaceLength);
      // 替换中间字符
      console.log(input.substr(0, start) + replaceStr + input.substr(start + replaceLength))
      return input.substr(0, start) + replaceStr + input.substr(start + replaceLength);
    },
    playAudio(item){
      this.activeUrl = item.filePath
      this.showPopup = true
    },
    remove(item,index) {
      delete this.audioList[index]
      this.audioList = this.audioList.filter(v => {
        return v
      })
      delete this.fileList3[index]
      this.fileList3 = this.fileList3.filter(v => {
        return v
      })
    },
    record() {
      let _this = this
      uni.chooseFile({
        count: 1, //默认100
        extension: ['.m4a', '.mp3'], //根据文件拓展名过滤，每一项都不能是空字符串。默认不过滤。
        success: function(res) {
          var tempFilePaths = res.tempFilePaths;
          console.log('mp3',res)
          console.log(JSON.stringify(tempFilePaths));
          _this.saveRecord(tempFilePaths[0])
        }
      });

    },
    saveRecord(param) {
      uni.showLoading({
        title: '上传中...'
      });
      uni.uploadFile({
        url: consts.API_BASE_URL + '/xsdcrm-wechat-api/riders/learningseek/uploadFile', // 上传地址
        filePath: param, // 要上传的文件路径
        name: 'file', // 上传文件对应的 key 值
        formData: {
          "file": param,   //接口需要的参数
          "type": 'recording'
        },
        header: {
          // 'Authorization': "Bearer " + JSON.parse(uni.getStorageSync('USERS_KEY')).access_token,
        },
        success: (uploadRes)=> {
          // 上传成功处理逻辑
          console.log(uploadRes);
          let result = JSON.parse(uploadRes.data)
          uni.hideLoading();
          uni.showToast({
            title: '上传成功'
          });
          const fileType = result.fileName.split('.').pop();
          const fileName = result.fileName.split('/').pop();
          this.audioList.push({filePath:(window.location.href.includes('/xsdcrm-wechat-ui/')?consts.API_BASE_URL+'/xsdcrm-static/upload/': '/profile/') + result.fileName})
          let params = {
            matialName:fileName,
            matialUrl:result.fileName,
            matialType:3,
          }
          this.fileList3.push(params)
        },
        fail: function(error) {
          // 上传失败处理逻辑
          console.log(error);
          uni.hideLoading();
          uni.showToast({
            title: '上传失败'
          });
        }
      });
    },
    uploadSuccess(result){
      const fileType = result.fileName.split('.').pop();
      const fileName = result.fileName.split('/').pop();
      let param = {
        matialName:fileName,
        matialUrl:result.fileName,
        matialType:2,
      }
      this.fileList2.push(param)
    },
    uploadRemove(index, lists, name) {
      delete this.fileList2[index]
      this.fileList2 = this.fileList2.filter(v => {
        return v
      })
    },
    onDelete(item,index,next){
      console.log(item)
      console.log(index)
      delete this.fileList1[index]
      this.fileList1 = this.fileList1.filter(v => {
        return v
      })
    },
    onSuccess(result){
      const fileType = result.fileName.split('.').pop();
      const fileName = result.fileName.split('/').pop();
      let param = {
        matialName:fileName,
        matialUrl:result.fileName,
        matialType:1,
      }
      this.fileList1.push(param)
      this.videoList.push((window.location.href.includes('/xsdcrm-wechat-ui/')?consts.API_BASE_URL+'/xsdcrm-static/upload/': '/profile/') + result.fileName)
    },
    leibieCallback(e) {
      let data = e[0];
      this.form.questionLabel = data.label;
      this.form.question = data.value;
      this.$forceUpdate();
    },
    async getBankDictList() {
      try {
        const res = await this.$api.riders.getDictList({type: 'riders_quersion_type'})
        if (res && res.code !== 200) {
          uni.showToast({
            title: res.msg,
            icon: "error",
          });
          return
        }
        if (res.data && res.data.length > 0) {
          res.data.forEach(item => {
            this.leibieList.push({
              value: item.dictValue,
              label: item.dictLabel,
            });
          })
        }
      } catch (e) {
        uni.showToast({
          title: '咨询分类下拉列表错误',
          icon: "error",
        });
      }
    },
    pickerCallback(e) {
      let data = e.data;
      this.siteItem = data[data.length - 1];
      this.form.sideName = this.siteItem.label;
      this.form.sideId = this.siteItem.id;
      console.log(this.form,this.siteItem)
      this.$forceUpdate();
      // this.getGuaList(this.siteItem.id);
      //流水号 //骑手id
    },
    async getGuaList(id) {
      uni.showLoading({
        title: '加载中...',
        mask: true,
      });
      this.actionNameList = [];
      let res = {}
      if (this.form.reason == '生活费' && this.form.loanAttribute == '运营干部') {
        res = await this.$api.jiekuan.getCityGuaList(id);
        uni.hideLoading();
      } else {
        res = await this.$api.jiekuan.getGuaList(id);
        uni.hideLoading();
      }
      if (isEmpty(res.data)) {
        uni.showToast({
          title: "当前站点无相关数据，请选择其他站点",
          icon: "error",
        });
      }

      res.data.forEach(element => {
        this.actionNameList.push({
          label: element.guaName,
          value: element.guaId,
          guaOpenid: element.guaOpenid,
          guaPhone: element.guaPhone,
          guaIdNumber: element.guaIdNumber
        })
      });
      console.log('this.actionNameList===>>>>',this.actionNameList)
      this.form.guaName = '';
    },
    async getDeptList() {
      let deptId = "0";
      // let source = uni.getStorageSync('source')
      // let res = await this.$api.notoken.listDeptHtml({ source });
      let res = await this.$api.notoken.listDeptCenterHtml({ deptId });
      this.auiPicker.data = res.data;
    },
    //显示picker多级联动弹窗
    showPickerMax(e) {
      this.auiPicker.layer = null;
      this.$refs.picker.open();
    },
  }
};
</script>

<style scoped>
  .consult-box{
    width: 100%;
    height: 100vh;
    padding:0 30rpx;
  }
  .newAddImg{
    width:166rpx;
    height: 166rpx;
    overflow: hidden;
    margin: 5px;
    background: #f4f5f6;
    position: relative;
    border-radius: 5px;
    display: flex;
    -webkit-box-align: center;
    -webkit-align-items: center;
    align-items: center;
    -webkit-box-pack: center;
    -webkit-justify-content: center;
    justify-content: center;
    flex-direction: column;
    align-items: center;
  }

  .list-item{
    width: 160rpx;
    height: 160rpx;
    overflow: hidden;
    margin: 5px;
    background: #f4f5f6;
    position: relative;
    border-radius: 5px;
    display: -webkit-box;
    display: -webkit-flex;
    display: flex;
    -webkit-box-align: center;
    -webkit-align-items: center;
    align-items: center;
    -webkit-box-pack: center;
    -webkit-justify-content: center;
    justify-content: center;
    flex-direction: column;
    color: #606266;
    font-size: 13px;
    view:nth-of-type(2){
      margin-top: 10px;
      line-height: 20px;
    }

  }

  .list-item-file{
    position:relative;
    .list-item-file-deleteImg{
      position: absolute;
      top: 0rpx;
      right: 14rpx;
      z-index:1;
    }
  }

  .list-item:active {
    /* 鼠标悬停时的样式 */
    background-color: #eee;
  }

  /deep/uni-audio{
    display: block;
  }
</style>
